package com.bee.shepherd.common.handler;

import com.google.common.collect.Lists;
import org.apache.http.*;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaolong.zhao on 18/1/26.
 * support:
 * Maven:org.apache.httpcomponents:httpcore:4.3
 * Maven:org.apache.httpcomponents:httpclient:4.3
 */
public class HttpNewVersionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpNewVersionHandler.class);
    private static CloseableHttpClient stdHttpClient;

    static {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(15000)
                .setCircularRedirectsAllowed(false).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(15000).setTcpNoDelay(true).build();

        stdHttpClient = HttpClientBuilder.create().setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) Chrome/27.0.1453.94 Safari/537.36")
                .setDefaultSocketConfig(socketConfig)
                .setMaxConnTotal(500).setMaxConnPerRoute(100)
                .setDefaultRequestConfig(requestConfig).build();
        //默认的HttpProcessorBuilder.create()支持自动解压缩以及cookie的管理
    }

    public static String doGet(String getUrl){
        HttpGet request = new HttpGet(getUrl);
        HttpResponse response = null;
        try {
            response = stdHttpClient.execute(request);
            HttpEntity entity = null;
            String content = null;
            try {
                StatusLine status = response.getStatusLine();
                entity = response.getEntity();
                if (status != null && status.getStatusCode() == 200) {
                    content = EntityUtils.toString(entity, Consts.UTF_8);
                    entity = null;
                } else {
                    content=EntityUtils.toString(entity,  Consts.UTF_8);
                }
            } finally {
                try {
                    EntityUtils.consume(entity);
                } catch (IOException ex) {
                    LOGGER.error("doGet error:",ex);
                }
            }
            return content;
        } catch (IOException e) {
            LOGGER.error("doGet error:",e);
            return null;
        }
    }

    public static String executePost(String voiceAsyncUrl,Map<String,String> params){
        HttpResponse response = null;
        HttpEntity entity = null;
        try {
            HttpPost httpPost=new HttpPost(voiceAsyncUrl);
            List<NameValuePair> nameValuePairs= Lists.newArrayList();
            for (Map.Entry<String, String> pair:params.entrySet()){
                nameValuePairs.add(new BasicNameValuePair(pair.getKey(),pair.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, Consts.UTF_8));
            response = stdHttpClient.execute(httpPost);
            String content = null;
            StatusLine status = response.getStatusLine();
            entity = response.getEntity();
            if (status != null && status.getStatusCode() == 200) {
                content = EntityUtils.toString(entity, Consts.UTF_8);
                entity = null;
            } else {
                content = EntityUtils.toString(entity,  Consts.UTF_8);
            }
            return content;
        } catch (Exception e) {
            LOGGER.error("doGet error:",e);
            return null;
        }finally {
            try {
                EntityUtils.consumeQuietly(entity);
            } catch (Exception ex) {
                LOGGER.error("doGet close error:",ex);
            }
        }
    }
}
